{
    // genertaor基本定义
    // 区别普通函数的地方: function后面添加*;
    // 函数题中 有yield语句
    let tell = function* () {
        yield 'a';
        yield 'b';
        return 'c'
    };

    let k = tell();

    console.log(k.next());
    console.log(k.next());
    console.log(k.next());
    console.log(k.next());
}

{
    // genertaor和iterator的关系, 部署一个iterator接口也可以用for...of
    let obj = {};
    obj[Symbol.iterator] = function* () {
        yield 1;
        yield 2;
        yield 3;
    }

    for (let value of obj) {
        console.log('value', value);
    }
}

{
    // 状态机函数;
    let state = function* () {
        while (1) {
            yield 'A';
            yield 'B';
            yield 'C';
        }
    }
    let status = state();
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
}

// {
//     let state = async function () {
//         while (1) {
//             await 'A';
//             await 'B';
//             await 'C';
//         }
//     }
//     let status = state();
//     console.log(status.next());
//     console.log(status.next());
//     console.log(status.next());
//     console.log(status.next());
//     console.log(status.next());
// }


{
    //  示例案例; 抽奖示例; 保证页面只能点三次; 不可多点
    let draw = function (count) {
        console.log(`剩余${count}次`)
    }

    let residue = function* (count) {
        while (count > 0) {
            count--;
            yield draw(count);
        }
    }

    let start = residue(3);
    let btn = document.createElement('button')
    btn.id = 'start'
    btn.textContent = 'start draw'
    document.body.append(btn)
    document.getElementById('start').addEventListener('click', function () {
        start.next()
    }, false)
}

{
    //示例2: 长轮询
    let ajax = function* () {
        yield new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve({ code: 0 })
            }, 1000)
        })
    }

    let pull = function () {
        let genertaor = ajax()
        let setp = genertaor.next()
        setp.value.then(function (d) {
            if (d.code != 0) {
                setTimeout(function () {
                    console.log('wait')
                    pull()
                }, 500)
            } else {
                console.log('success====')
            }
        })
    }
    pull()

}